import 'package:flutter/material.dart';
import '../models/fishing_spot.dart';
import '../services/home_service.dart';

class FishingProvider with ChangeNotifier {
  final HomeService _homeService = HomeService();

  List<FishingSpot> _allSpots = [];
  List<FishingSpot> _recommendedSpots = [];
  bool _isLoading = false;
  bool _hasLoadedOnce = false; // 标记是否已经加载过一次

  // Getters
  List<FishingSpot> get allSpots => _allSpots;
  List<FishingSpot> get recommendedSpots => _recommendedSpots;
  bool get isLoading => _isLoading;
  bool get hasLoadedOnce => _hasLoadedOnce;

  // 加载所有钓场数据
  Future<void> loadFishingSpots({bool forceRefresh = false}) async {
    // 如果已经加载过且不是强制刷新，则直接返回
    if (_hasLoadedOnce && !forceRefresh) {
      return;
    }

    _isLoading = true;
    notifyListeners();

    try {
      // 获取钓场列表
      final spots = await _homeService.getFishingSpotList(
        pageSize: 100,
        userLatitude: 23.1291, // 广州天河区坐标
        userLongitude: 113.2644,
      );

      _allSpots = spots;
      _generateRecommendedSpots();
      _hasLoadedOnce = true;
    } catch (e) {
      _allSpots = [];
      _recommendedSpots = [];
    }

    _isLoading = false;
    notifyListeners();
  }

  // 生成推荐钓场（按距离最近+评分最高排序，选前5个）
  void _generateRecommendedSpots() {
    if (_allSpots.isEmpty) {
      _recommendedSpots = [];
      return;
    }

    // 复制一份数据进行排序
    final sortedSpots = List<FishingSpot>.from(_allSpots);
    
    // 按距离最近+评分最高排序，选前5个
    sortedSpots.sort((a, b) {
      // 综合评分：距离权重0.4，评分权重0.6
      double scoreA = (1 / (a.distance + 0.1)) * 0.4 + a.rating * 0.6;
      double scoreB = (1 / (b.distance + 0.1)) * 0.4 + b.rating * 0.6;
      return scoreB.compareTo(scoreA);
    });

    _recommendedSpots = sortedSpots.take(5).toList();
  }

  // 刷新数据（下拉刷新时调用）
  Future<void> refreshData() async {
    await loadFishingSpots(forceRefresh: true);
  }

  // 搜索和筛选钓场
  List<FishingSpot> getFilteredSpots({
    String searchQuery = '',
    String filter = 'all', // all, nearby, rating, price
    String difficulty = 'all', // all, beginner, intermediate, advanced
  }) {
    List<FishingSpot> filtered = List.from(_allSpots);

    // 搜索过滤
    if (searchQuery.isNotEmpty) {
      filtered = filtered.where((spot) {
        return spot.name.toLowerCase().contains(searchQuery.toLowerCase()) ||
               spot.address.toLowerCase().contains(searchQuery.toLowerCase()) ||
               spot.fishTypes.any((type) => type.toLowerCase().contains(searchQuery.toLowerCase()));
      }).toList();
    }

    // 难度过滤
    if (difficulty != 'all') {
      filtered = filtered.where((spot) => spot.difficulty == difficulty).toList();
    }

    // 排序过滤
    switch (filter) {
      case 'nearby':
        filtered.sort((a, b) => a.distance.compareTo(b.distance));
        break;
      case 'rating':
        filtered.sort((a, b) => b.rating.compareTo(a.rating));
        break;
      case 'price':
        // 这里可以根据价格排序，暂时按名称排序
        filtered.sort((a, b) => a.name.compareTo(b.name));
        break;
      default:
        // 默认按综合评分排序
        filtered.sort((a, b) {
          double scoreA = (1 / (a.distance + 0.1)) * 0.4 + a.rating * 0.6;
          double scoreB = (1 / (b.distance + 0.1)) * 0.4 + b.rating * 0.6;
          return scoreB.compareTo(scoreA);
        });
    }

    return filtered;
  }
}